import 'dart:convert';
import 'dart:math';
import 'dart:ui';
import 'package:audioplayers/audio_cache.dart';
import 'package:bruno/bruno.dart';
import 'package:demo/dto/entity/theme.dart';
import 'package:demo/service/resouceService.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:getwidget/getwidget.dart';
import 'package:share/share.dart';

class CalculatorA extends StatefulWidget {
  @override
  _calculator createState() => _calculator();
}

class _calculator extends State<CalculatorA> {
  // 按鍵音
  AudioCache audioCache = AudioCache();
  void playSound() {
    audioCache.play('../sounds/click.wav');
  }

// 計算log
  List log = [];
  // 查看計算記錄
  bool isShowLog = false;
//  計算數
  List tempList = [];
// 計算數2
  List tempList2 = [];
// 得數
  num sum = 0;
// 計算方法
  String methods = "";
// 當前計算方法
  String actionNethods = "";
// 計算類型
  List type = ["+", "-", "*", "÷"];
  // 當前索引
  int index = 0;
  // % 計數器
  int totalNum = 0;
  // 默認背景圖
  String bgImg = "";

// 選中數值方法
  void selectNum(value) {
    playSound();
    if (type.indexOf(this.actionNethods) >= 0) {
      setState(() {
        this.index = 1;
        if (this.tempList2.length == 1 &&
            this.tempList2[0] == 0 &&
            value != '.') {
          this.tempList2.removeAt(0);
        }
        this.tempList2.add(value);
      });
    } else {
      setState(() {
        this.index = 0;
        if (this.tempList.length == 1 &&
            this.tempList[0] == 0 &&
            value != '.') {
          this.tempList.removeAt(0);
        }
        this.tempList.add(value);
      });
    }
  }

// 合算運算方式
  void sumNum(v) {
    this.playSound();
    if (this.tempList.length == 0) {
      print("我要結束掉這個運行");
      return;
    } else {
      setState(() {
        // 兩個數值其中一個不存在，不計算
        if (tempList.length == 0 || tempList2.length == 0) {
          return;
        }

        double a = double.parse(tempList.join().toString());
        double b = double.parse(tempList2.join().toString());

        methods = actionNethods;

        if (methods == "÷") {
          if (b == 0) {
            return;
          }
          sum = a / b;
        } else if (methods == "+") {
          sum = a + b;
        } else if (methods == "-") {
          sum = a - b;
        } else if (methods == "*") {
          sum = a * b;
        }

// 計算日誌記錄
        this
            .log
            .add({"value1": a, "value2": b, "methos": methods, "result": sum});

        this.tempList = [sum];
        this.tempList2 = [];
        this.methods = "=";
        this.actionNethods = "";
      });
    }
  }

  // 顯示歷史記錄
  void showLogList() {
    setState(() {
      this.isShowLog = false;
    });
  }

  // 清空歷史記錄
  void clearLogList() {
    setState(() {
      this.log = [];
    });
  }

// 復制功能
  void copyInfo() {
    GFToast.showToast("長按復制哦", context);
  }

  // 設置背景圖
  void setBgimg(v) {
    setState(() {
      if (v != null) {
        this.bgImg = v;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    dynamic obj = ModalRoute.of(context)?.settings.arguments;

    if (obj != "") {
      setBgimg(obj);
    }
    return Container(
      // 全屏背景
      decoration: bgImg == ""
          ? BoxDecoration(
              gradient: LinearGradient(colors: [
              Color.fromARGB(255, 2, 47, 84),
              Color.fromARGB(255, 2, 60, 131)
            ]))
          : BoxDecoration(
              image: DecorationImage(
                  image: NetworkImage(this.bgImg), fit: BoxFit.cover)),

      // 應用截體
      child: new BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0),
          child: Container(
            child: Scaffold(
              backgroundColor: Colors.transparent,
              appBar: new AppBar(
                backgroundColor: Colors.transparent,
                elevation: 0,
                title: Text(
                  "計算器 HD",
                  style: const TextStyle(color: Colors.white),
                ),
                actions: [
                  IconButton(
                    icon: Icon(Icons.menu),
                    tooltip: "查看計算記錄",
                    color: Colors.white,
                    onPressed: () async {
                      // 功能選擇
                      BrnDialogManager.showMoreButtonDialog(
                        context,
                        actions: ["設置", "清空計算記錄", "推薦給大家"],
                        showIcon: false,
                        indexedActionClickCallback: (index) {
                          if (index == 0) {
                            Navigator.of(context).pop();
                            Navigator.pushNamed(context, "/setting");
                          } else if (index == 1) {
                            this.clearLogList();
                            Navigator.of(context).pop();
                          } else if (index == 2) {
                            // 分享功能
                            Share.share("Flutter");
                          }
                        },
                      );
                    },
                  ),
                ],
              ),

              // ---------------
              body: Container(
                  child: Column(
                children: [
                  // 計算記錄列表
                  Offstage(
                    offstage: false,
                    child: Container(
                      height: 410,
                      color: Color.fromARGB(76, 230, 230, 230),
                      child: ListView.builder(
                          itemCount: log.length,
                          itemBuilder: (context, index) {
                            String title = log[index]['value1'].toString() +
                                ' ' +
                                log[index]['methos'] +
                                ' ' +
                                log[index]['value2'].toString();

                            String result = (log[index]['result'].toString());
                            return Container(
                                margin: EdgeInsets.only(left: 0),
                                child: Container(
                                  margin: EdgeInsets.only(right: 0),
                                  child: GFListTile(
                                    title: Container(
                                      width: double.infinity,
                                      height: 60,
                                      margin:
                                          EdgeInsets.only(top: 0, bottom: 0),
                                      child: ListTile(
                                        title: Text(
                                          result,
                                          textAlign: TextAlign.right,
                                          style: TextStyle(
                                              fontWeight: FontWeight.bold,
                                              fontSize: 20),
                                        ),
                                        subtitle: Text(title,
                                            textAlign: TextAlign.right),
                                      ),
                                      color: Color.fromARGB(53, 13, 2, 4),
                                    ),
                                    onLongPress: () {
                                      BrnDialogManager.showConfirmDialog(
                                        context,
                                        title: "是否複製該條記錄",
                                        cancel: '取消',
                                        confirm: '确定',
                                        message: "",
                                        onConfirm: () {
                                          //複製
                                          Clipboard.setData(ClipboardData(
                                              text: title +
                                                  '-' +
                                                  '----' +
                                                  result));
                                          print("你選擇了複製");
                                          Navigator.of(context).pop();
                                        },
                                        onCancel: () {
                                          Navigator.of(context).pop();
                                        },
                                      );
                                    },
                                  ),
                                ));
                          }),
                    ),
                  ),

                  // 結果容器
                  GFListTile(
                      margin: EdgeInsets.only(left: 5, right: 5),
                      title: new Container(
                        alignment: Alignment.centerRight,
                        height: 50,
                        padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                        color: Color.fromARGB(216, 194, 194, 194),
                        child: Text(
                          "" +
                              this.tempList.join('').toString() +
                              this.actionNethods.toString() +
                              this.tempList2.join('').toString(),
                          style: TextStyle(
                            fontSize: 25,
                          ),
                          maxLines: 1,
                        ),
                      )),

                  // 按紐
                  GFButtonBar(children: [
                    GFButton(
                        size: GFSize.LARGE,
                        onPressed: () {
                          playSound();
                          setState(() {
                            this.tempList = [0];
                            this.tempList2 = [];
                            this.methods = "";
                            this.sum = 0;
                            this.actionNethods = "";
                            this.totalNum = 0;
                          });
                        },
                        text: "Ac"),
                    GFButton(
                        size: GFSize.LARGE,
                        onPressed: () {
                          playSound();
                          setState(() {
                            // 正負轉換
                            if (this.tempList.length > 0) {
                              print(this.tempList.toString());
                              if (this.tempList[0] == "-") {
                                this.tempList.remove('-');
                              } else {
                                this.tempList.insert(0, '-');
                              }
                            }
                          });

                          print(this.tempList);
                        },
                        text: "+/-"),
                    GFButton(
                        size: GFSize.LARGE,
                        onPressed: () {
                          playSound();
                          if (this.tempList.length == 0 &&
                              this.tempList2.length == 0) {
                            return;
                          }
                          this.totalNum += 1;
                          List t =
                              this.index == 0 ? this.tempList : this.tempList2;
                          num n =
                              double.parse(t.join()) / pow(100, this.totalNum);
                          setState(() {
                            this.sum = n;
                            this.tempList[0] = n;
                          });
                        },
                        text: "%"),
                    GFButton(
                      size: GFSize.LARGE,
                      color: Color.fromARGB(255, 253, 117, 26),
                      onPressed: () {
                        playSound();
                        setState(() {
                          if (this.tempList.length == 0) {
                            return;
                          }
                          if (this.tempList.length > 0 &&
                              this.tempList2.length > 0) {
                            this.sumNum(this.actionNethods);
                          }
                          this.actionNethods = "÷";
                        });
                      },
                      child: Text(
                        "÷",
                        style: TextStyle(fontSize: 25, color: Colors.white),
                      ),
                    ),
                  ]),
                  // 按紐
                  GFButtonBar(children: [
                    GFButton(
                      size: GFSize.LARGE,
                      onPressed: () {
                        selectNum(1);
                      },
                      child: Text(
                        "1",
                        style: TextStyle(fontSize: 25, color: Colors.white),
                      ),
                    ),
                    GFButton(
                      size: GFSize.LARGE,
                      onPressed: () {
                        selectNum(2);
                      },
                      child: Text(
                        "2",
                        style: TextStyle(fontSize: 25, color: Colors.white),
                      ),
                    ),
                    GFButton(
                      size: GFSize.LARGE,
                      onPressed: () {
                        selectNum(3);
                      },
                      child: Text(
                        "3",
                        style: TextStyle(fontSize: 25, color: Colors.white),
                      ),
                    ),
                    GFButton(
                      size: GFSize.LARGE,
                      color: Color.fromARGB(255, 253, 117, 26),
                      onPressed: () {
                        playSound();
                        setState(() {
                          if (this.tempList.length == 0) {
                            return;
                          }
                          if (this.tempList.length > 0 &&
                              this.tempList2.length > 0) {
                            this.sumNum(this.actionNethods);
                          }
                          this.actionNethods = "+";
                        });
                      },
                      child: Text(
                        "+",
                        style: TextStyle(fontSize: 25, color: Colors.white),
                      ),
                    ),
                  ]),
                  GFButtonBar(children: [
                    GFButton(
                      size: GFSize.LARGE,
                      onPressed: () {
                        selectNum(4);
                      },
                      child: Text(
                        "4",
                        style: TextStyle(fontSize: 25, color: Colors.white),
                      ),
                    ),
                    GFButton(
                      onPressed: () {
                        selectNum(5);
                      },
                      child: Text(
                        "5",
                        style: TextStyle(fontSize: 25, color: Colors.white),
                      ),
                    ),
                    GFButton(
                      size: GFSize.LARGE,
                      onPressed: () {
                        selectNum(6);
                      },
                      child: Text(
                        "6",
                        style: TextStyle(fontSize: 25, color: Colors.white),
                      ),
                    ),
                    GFButton(
                      size: GFSize.LARGE,
                      color: Color.fromARGB(255, 253, 117, 26),
                      onPressed: () {
                        playSound();
                        print(this.tempList.length);
                        if (this.tempList.length == 0) {
                          return;
                        }
                        setState(() {
                          if (this.tempList.length > 0 &&
                              this.tempList2.length > 0) {
                            this.sumNum(this.actionNethods);
                          }
                          this.actionNethods = "-";
                        });
                      },
                      child: Text(
                        "-",
                        style: TextStyle(fontSize: 25, color: Colors.white),
                      ),
                    ),
                  ]),
                  GFButtonBar(children: [
                    GFButton(
                      size: GFSize.LARGE,
                      onPressed: () {
                        selectNum(7);
                      },
                      child: Text(
                        "7",
                        style: TextStyle(fontSize: 25, color: Colors.white),
                      ),
                    ),
                    GFButton(
                      size: GFSize.LARGE,
                      onPressed: () {
                        selectNum(8);
                      },
                      child: Text(
                        "8",
                        style: TextStyle(fontSize: 25, color: Colors.white),
                      ),
                    ),
                    GFButton(
                      size: GFSize.LARGE,
                      onPressed: () {
                        selectNum(9);
                      },
                      child: Text(
                        "9",
                        style: TextStyle(fontSize: 25, color: Colors.white),
                      ),
                    ),
                    GFButton(
                      size: GFSize.LARGE,
                      color: Color.fromARGB(255, 253, 117, 26),
                      onPressed: () {
                        playSound();
                        setState(() {
                          if (this.tempList.length == 0) {
                            return;
                          }
                          if (this.tempList.length > 0 &&
                              this.tempList2.length > 0) {
                            this.sumNum(this.actionNethods);
                          }
                          this.actionNethods = "*";
                        });
                      },
                      child: Text(
                        "*",
                        style: TextStyle(fontSize: 25, color: Colors.white),
                      ),
                    ),
                  ]),
                  GFButtonBar(
                    children: [
                      GFButton(
                        onPressed: () {
                          Navigator.pushNamed(context, "/theme");
                        },
                        child: Text(
                          "主",
                          style: TextStyle(fontSize: 25, color: Colors.white),
                        ),
                      ),
                      GFButton(
                        size: GFSize.LARGE,
                        onPressed: () {
                          if (this.sum == 0 &&
                              this.tempList.length == 1 &&
                              this.tempList[0] == 0) {
                            playSound();
                            return;
                          }
                          selectNum(0);
                        },
                        child: Text(
                          "0",
                          style: TextStyle(fontSize: 25, color: Colors.white),
                        ),
                      ),
                      GFButton(
                        size: GFSize.LARGE,
                        onPressed: () {
                          playSound();
                          // 判斷指定位置是否包涵小數點
                          print("當前${index}");
                          if (this.index == 0) {
                            if (this.tempList.contains(".")) {
                              return;
                            }
                          } else if (this.index == 1) {
                            if (this.tempList2.contains(".")) {
                              print(this.tempList2);
                              return;
                            }
                          }
                          selectNum(".");
                        },
                        child: Text(
                          ".",
                          style: TextStyle(fontSize: 25, color: Colors.white),
                        ),
                      ),
                      GFButton(
                        size: GFSize.LARGE,
                        color: Color.fromARGB(255, 253, 117, 26),
                        onPressed: () {
                          playSound();
                          if (this.tempList.length > 0 &&
                              this.tempList2.length > 0) {
                            this.sumNum("no");
                          }
                        },
                        child: Text(
                          "=",
                          style: TextStyle(fontSize: 25, color: Colors.white),
                        ),
                      ),
                    ],
                  ),
                ],
              )),
            ),
          )),
    );
  }
}
